<!DOCTYPE html>
<html>
<head>
    <title>鹿鹿泽健身项目更新</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
</head>
<body>
    {% include 'show_ins_info.html' %}
    <div >
        <h1 style="color:rgb(67, 115, 219)">增加训练项目</h1>

        <div class="form-row"><h4 style="width:80px;">训练类型</h4><select id="form" onchange="showAllItem();handleInput();"></select></div>
        <div class="form-row"><h4 style="width:80px;">综合分类</h4><select id="category" onchange="handleInput();"></select></div>
        <div class="form-row"><h4 style="width:80px;">训练部位</h4><select id="muscle" onchange="handleInput();"></select></div>
        <div class="form-row"><h4 style="width:80px;">训练名称</h4><input id="actionName" style="width:120px;" oninput="handleInput();"><div id="actionError"></div></div>
        <div id="similarResult"></div>
        <div id="resultInfo"></div>
        

        
        <div style="margin-left:8px;">
            <hr>
            <button id="submit" onclick="submit()" style="margin-top:10px;">提交</button>
        </div>
        
    </div>


    <script src="../static/js/common.js"></script>
    <script>
        let trainItemData;

        document.addEventListener("DOMContentLoaded",function(){
            // loginCheck();
            const insInfo=hideInsSelectBlockAndGetInsInfo();
            insName=insInfo['sessionInsName'];
            insId=insInfo['sessionInsId'];
            insRole=insInfo['sessionInsRole'];        
            
                

            fetch('/get_train_list', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
            })
            .then(response => response.json())
            .then(data => {
                //将data赋值给块变量cus_list，供后面的handleInput使用
                console.log(data);
                trainItemData=data;
                let form=[];
                Object.keys(data['by_form']).forEach(key=>{
                    if(!form.includes(key)){
                        form.push(key);
                    }
                });

                const formOrder=['抗阻训练','有氧训练','综合训练','伸展拉伸'];
                form.sort((a,b)=>{
                    return formOrder.indexOf(a)-formOrder.indexOf(b)
                });

                showItem('form',form);
                showAllItem(data);

            })
            .catch(error => console.error('Error:', error));        
            
            const submitBtn=document.getElementById('submit');
            submitBtn.disabled=true;
            document.getElementById('resultInfo').innerHTML='';

        });


        function showAllItem(dataInput){
            let data;
            if(!dataInput){
                data=trainItemData;
            }else{
                data=dataInput;
            }
            const formName=document.getElementById('form').value;
            let catArr=[];
            Object.keys(data['by_category']).forEach(item=>{
                data['by_category'][item].forEach(opt=>{
                    if(opt[0]===formName && !catArr.includes(item)){
                        catArr.push(item);
                    }
                });
            });

            showItem('category',catArr);
            // const catEvent=new Event('change');
            // const catSel=document.getElementById('category');
            // catSel.dispatchEvent(catEvent);

            let muscleArr=[];
            Object.keys(data['by_muscle']).forEach(item=>{
                data['by_muscle'][item].forEach(opt=>{
                    if(opt[0]===formName && !muscleArr.includes(item)){
                        muscleArr.push(item);
                    }
                });
            });
            showItem('muscle',muscleArr);
            // const muscleEvent=new Event('change');
            // const muscleSel=document.getElementById('muscle');
            // muscleSel.dispatchEvent(muscleEvent);

        }

        function showItem(divName,data){
            const sel=document.getElementById(divName);
            sel.innerHTML='';
            data.forEach(item=>{
                const opt=document.createElement('option');
                opt.value=item;
                opt.text=item;
                sel.appendChild(opt);
            });
        }

        function handleInput() {
            const submitBtn=document.getElementById('submit');
            const formName=document.getElementById('form').value;
            const category=document.getElementById('category').value;
            const muscle=document.getElementById('muscle').value;
            
            const similarResult=document.getElementById('similarResult');
            // 清空列表
            similarResult.innerHTML = "";
          
            

            // 获取输入框中的值
            const searchTerm = document.getElementById("actionName").value.trim();
            if(searchTerm.length===0){
                submitBtn.disabled=true;
            }else{
                submitBtn.disabled=false;
            }
            const UpperSearchTerm=searchTerm.toUpperCase();
            if (UpperSearchTerm === "") {
                similarResult.style.display = "none";
                return; // 输入框为空，不做处理
            }else{
                similarResult.style.display = "block";
            }

            // 清空提示
            const actionErrorBox=document.getElementById('actionError');
            actionErrorBox.innerHTML = "";

            if (UpperSearchTerm === "") {
                actionErrorBox.style.display = "none";
                return; // 输入框为空，不做处理
            }else{
                actionErrorBox.style.display = "block";
            }

            // 遍历给定的数组，进行模糊匹配
            let repeated='false';
            Object.keys(trainItemData['by_action_name']).forEach(name=>{
                // if(repeated==='false' && name.includes(searchTerm) && trainItemData['by_action_name'][name][0]===formName && trainItemData['by_action_name'][name][1]===muscle && trainItemData['by_action_name'][name][2]===category){
                if(repeated==='false' && name.includes(UpperSearchTerm)){
                    const listItem = document.createElement("li");
                    listItem.textContent = name;                    
                    similarResult.appendChild(listItem);
                    similarResult.classList.add('train-item-list');
                    similarResult.style.top='288px';
                }else{
                    actionErrorBox.innerHTML='';
                }

                // if (name===searchTerm && trainItemData['by_action_name'][name][0]===formName && trainItemData['by_action_name'][name][1]===muscle && trainItemData['by_action_name'][name][2]===category) {  
                if (name===searchTerm) {  
                        similarResult.style.display='none';
                        repeated='true';          
                    }
            });

            const listItems = similarResult.getElementsByTagName('li');
            if(listItems.length>0){
                const firstListItem = document.getElementById('similarResult').querySelector('li');
                const trainItemTitle=document.createElement('div');
                trainItemTitle.id='trainItemTitle';
                
                trainItemTitle.textContent='- 已有的相似训练项目 -';
                firstListItem.insertAdjacentElement('beforebegin',trainItemTitle);
            }

            if(repeated==='true'){
                actionErrorBox.innerHTML='<span style="color:red;margin-left:10px;font-size:14px;">训练项目重复</span>';   
                submitBtn.disabled=true;

            }else{
                actionErrorBox.innerHTML='';   
                submitBtn.disabled=false;
            }
        
            
        }

        function submit(){
            const formName=document.getElementById('form').value;
            const category=document.getElementById('category').value;
            const muscle=document.getElementById('muscle').value;
            const actionName=document.getElementById('actionName').value.trim();
            const insIdPage=insId;
            const currentTime=new Date()
            const currentTimeStr=dateToString(currentTime,'dateTime');
            const data={
                'form':formName,
                'category':category,
                'muscle':muscle,
                'action_name':actionName,
                'opr_id':insIdPage,
                'opr_time':currentTimeStr
            }

            console.log('train item data:',data)

            if(formName!=='' && category!=='' && muscle!=='' && actionName!==''){
                fetch('/deal_update_train_item',{
                    method:'POST',
                    headers:{
                        'Content-Type':'application/json'
                    },
                    body: JSON.stringify(data)
                })
                .then(response => response.json())
                .then(data => {           
                    console.log(data['res'])
                    if(data['res']==='ok'){
                        document.getElementById('resultInfo').innerHTML=`<span style="color:blue;">【${actionName}】 已更新至数据库</span>`;
                        // alert(`【${actionName}】已更新至数据库`);
                    }else{
                        document.getElementById('resultInfo').innerHTML='<span style="color:red;">更新错误，请联系管理员。</span>'
                    }
                })
                .catch(error => console.error('Error:', error));
            }else{
                document.getElementById('resultInfo').innerHTML='<span style="color:red;">训练名称为空</span>'
            }


        }


        
    </script>
</body>